import 'package:flutter/material.dart';
import 'package:ichinesereader/models/student/AssignmentDetail.dart';
import 'package:ichinesereader/models/student/StudentMiniJson.dart';
import 'package:ichinesereader/pages/teacher/homeworkProgress.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:just_the_tooltip/just_the_tooltip.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import '../../themes/pageStyles.dart';

// ignore: must_be_immutable
class HomeworkOngoingDataGrid extends StatelessWidget {
  HomeworkOngoingDataGrid(this.isTeacher, this.assignmentItems);

  List<AssignmentDetail> assignmentItems;
  bool isTeacher = true;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();
  final PageStyles _pageStyles = PageStyles();

  @override
  Widget build(BuildContext context) {
    Log.debug('build AssingmentOngoingDataGrid');
    return Container(
      //margin: EdgeInsets.fromLTRB(0.0, 3.0, 12.0, 33.0),
      child: _buildDataGrid(),
    );
  }

  Container _buildDataGrid() {
    return Container(
      decoration: _pageStyles.dataGridBackground(),
      child: Container(
        margin: EdgeInsets.all(12.0),
        decoration: _pageStyles.dataGridForground(),
        child: SfDataGrid(
          source: AssignmentDataGridSource(
              items: assignmentItems, isTeacher: isTeacher),
          isScrollbarAlwaysShown: true,
          onQueryRowHeight: (row) {
            return row.rowIndex == 0 ? 50.0 : 49.0;
          },
          //设置表头高度
          showCheckboxColumn: false,
          allowFiltering: true,
          checkboxColumnSettings: Get.isDarkMode
              ? DataGridCheckboxColumnSettings(
                  backgroundColor: Color(0xff0a0e21),
                )
              : DataGridCheckboxColumnSettings(
                  backgroundColor: Colors.blue[50]),
          allowSorting: true,
          allowTriStateSorting: true,
          allowSwiping: false,
          controller: _dataGridController,
          selectionMode: SelectionMode.none,
          navigationMode: GridNavigationMode.row,
          columns: <GridColumn>[
            GridColumn(
              width: 240,
              columnName: 'Task',
              label: buildDataGridColumnLabel('Task'),
            ),
            GridColumn(
              columnName: 'Status',
              //allowFiltering: false,
              width: isWebOrDesktop ? 140 : 140,
              label: buildDataGridColumnLabel('Status'),
            ),
            GridColumn(
              columnName: 'FinishedStudents',
              width: isWebOrDesktop ? 190.0 : 120.0,
              allowFiltering: false,
              label: buildDataGridColumnLabel('FinishedStudents'),
            ),
            GridColumn(
              columnName: 'RequiredStudents',
              visible: false,
              label: Container(),
            ),
            GridColumn(
              columnName: 'RequiredReadings',
              width: isWebOrDesktop ? 190.0 : 120.0,
              allowFiltering: false,
              label: buildDataGridColumnLabel('RequiredReadings'),
            ),
            GridColumn(
              columnName: 'NumBooks',
              visible: false,
              label: Container(),
            ),
            GridColumn(
              columnName: 'CreateDate',
              allowFiltering: false,
              width: 160,
              label: buildDataGridColumnLabel('CreateDate'),
            ),
            GridColumn(
              columnName: 'StartDate',
              allowFiltering: false,
              width: 160,
              label: buildDataGridColumnLabel('StartDate'),
            ),
            GridColumn(
              columnName: 'DueDate',
              allowFiltering: false,
              width: 160,
              label: buildDataGridColumnLabel('DueDate'),
            ),
            GridColumn(
              columnName: 'Students',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('Students'),
            ),
            GridColumn(
              columnName: 'Id',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('Id'),
            ),
          ],
        ),
      ),
    );
  }
}

class AssignmentDataGridSource extends DataGridSource {
  AssignmentDataGridSource(
      {required List<AssignmentDetail> items, required this.isTeacher}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(columnName: 'Task', value: dataGridRow.name),
              DataGridCell<String>(
                  columnName: 'Status',
                  value: dataGridRow.status?.toUpperCase()),
              DataGridCell<int>(
                  columnName: 'FinishedStudents',
                  value: dataGridRow.completedStudents),
              DataGridCell<int>(
                  columnName: 'RequiredStudents',
                  value: dataGridRow.studentUserNames?.length ?? 0),
              DataGridCell<int>(
                  columnName: 'RequiredReadings',
                  value: dataGridRow.noOfBookToBeRead),
              DataGridCell<int>(
                  columnName: 'NumBooks', value: dataGridRow.numBooks),
              DataGridCell<int>(
                columnName: 'CreateDate',
                value: dataGridRow.createDate,
              ),
              DataGridCell<int>(
                columnName: 'StartDate',
                value: dataGridRow.startDate,
              ),
              DataGridCell<int>(
                columnName: 'DueDate',
                value: dataGridRow.endDateUtc,
              ),
              DataGridCell<List<StudentMiniJson>>(
                  columnName: 'Students',
                  value: dataGridRow.studentMiniJsoNs ?? <StudentMiniJson>[]),
              DataGridCell<String>(columnName: 'Id', value: dataGridRow.id),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];
  bool isTeacher = true;

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    String studentNames = '';
    List<StudentMiniJson> students = row
        .getCells()
        .where((element) => element.columnName == 'Students')
        .first
        .value;
    if (students.isNotEmpty) {
      students.forEach((s) {
        studentNames = studentNames +
            s.lastName.toString() +
            ' ' +
            s.firstName.toString() +
            ', ';
      });

      if (studentNames.length > 2) {
        studentNames = studentNames.substring(0, studentNames.length - 2);
      }
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'CreateDate' ||
              dataGridCell.columnName == 'StartDate' ||
              dataGridCell.columnName == 'DueDate') {
            if (dataGridCell.value > 0) {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 6.0),
                  child: Text(
                    DateFormat('yyyy-MM-dd kk:mm').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.fade,
                    style: Get.textTheme.bodySmall,
                  ));
            } else {
              return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    ' - ',
                    overflow: TextOverflow.fade,
                    style: Get.textTheme.bodySmall,
                  ));
            }
          } else if (dataGridCell.columnName == 'Status') {
            String _status = dataGridCell.value
                .toString()
                .replaceAll('LIVE', 'OPEN')
                .replaceAll('PAST', 'CLOSED')
                .replaceAll('COMPLETED', 'CLOSED');
            return Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: 6.0),
              child: Text(
                _status,
                overflow: TextOverflow.fade,
                style: Get.textTheme.bodySmall,
              ),
            );
          } else if (dataGridCell.columnName == 'Task') {
            return Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: 6.0),
              child: GestureDetector(
                onTap: () {
                  if (isTeacher) {
                    var id = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    Get.to(() =>
                        HomeworkProgress(name: dataGridCell.value, id: id));
                  }
                },
                child: isTeacher
                    ? JustTheTooltip(
                        backgroundColor: Get.isDarkMode
                            ? Get.theme.primaryColorDark
                            : Get.theme.primaryColorLight,
                        preferredDirection: AxisDirection.right,
                        elevation: 4.0,
                        content: Container(
                          padding: EdgeInsets.all(8.0),
                          width: 480,
                          color: Colors.transparent,
                          child: Text(
                            studentNames,
                            style: TextStyle(
                              fontSize: 12,
                              color: Get.isDarkMode
                                  ? Colors.black
                                  : Colors.black87,
                            ),
                          ),
                        ),
                        child: Text(
                          dataGridCell.value.toString(),
                          style: Get.theme.textTheme.titleLarge,
                          overflow: TextOverflow.ellipsis,
                        ),
                      )
                    : Text(
                        dataGridCell.value.toString(),
                        style: Get.theme.textTheme.titleLarge,
                        overflow: TextOverflow.ellipsis,
                      ),
              ),
            );
          } else if (dataGridCell.columnName == "FinishedStudents") {
            var stuNo = row
                .getCells()
                .where((element) => element.columnName == 'RequiredStudents')
                .first
                .value;
            return Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  '${dataGridCell.value.toString()}/${stuNo.toString()}',
                  overflow: TextOverflow.fade,
                  style: Get.textTheme.bodySmall,
                ));
          } else if (dataGridCell.columnName == "RequiredReadings") {
            var bookNo = row
                .getCells()
                .where((element) => element.columnName == 'NumBooks')
                .first
                .value;
            return Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  '${dataGridCell.value.toString()}/${bookNo.toString()}',
                  overflow: TextOverflow.fade,
                  style: Get.textTheme.bodySmall,
                ));
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 6.0),
                child: Text(
                  dataGridCell.value.toString(),
                  softWrap: true,
                  overflow: TextOverflow.fade,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
